<template>
  <div class="chat-container page-container">
    <div class="chat-header">
      <div class="ai-info">
        <el-avatar :size="40" src="/ai-avatar.png" />
        <div class="ai-title">
          <h3>AI心理咨询师</h3>
          <span class="status">在线</span>
        </div>
      </div>
    </div>

    <el-scrollbar class="message-area" height="calc(100vh - 180px)" ref="scrollbarRef">
      <div class="message-list">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message-bubble"
          :class="{ 'ai-message': msg.isAI }"
        >
          <div class="message-content">
            <div class="message-text markdown-body" v-html="formatMessage(msg.content)"></div>
            <span class="message-time">{{ formatTime(msg.time) }}</span>
          </div>
        </div>
      </div>
    </el-scrollbar>

    <div class="input-area">
      <el-form @submit.prevent="sendMessage">
        <el-input
          v-model="newMessage"
          placeholder="输入你的问题..."
          type="textarea"
          :rows="3"
          resize="none"
          @keydown.enter.prevent="sendMessage"
        />
        <div class="send-button">
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            :disabled="!newMessage.trim()"
          >
            <el-icon><Position /></el-icon>
            发送
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { chat } from "@/api/test.js"
import { getUser } from "@/store/userStore.js"
import { Position } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (__) {}
    }
    return '' // 使用默认的转义
  }
})

const scrollbarRef = ref(null)
const loading = ref(false)
const newMessage = ref('')
const messages = ref([
  {
    content: '你好，我是AI心理咨询师，有什么可以帮您？',
    time: new Date(),
    isAI: true
  }
])

const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}

const formatMessage = (content) => {
  // 处理换行和制表符
  const formattedContent = content
    .replace(/\\n/g, '\n')
    .replace(/\\t/g, '\t')
    .replace(/\n/g, '<br>')
    .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')

  // 将Markdown转换为HTML
  return md.render(formattedContent)
}

const scrollToBottom = async () => {
  await nextTick()
  if (scrollbarRef.value) {
    scrollbarRef.value.setScrollTop(scrollbarRef.value.wrapRef.scrollHeight)
  }
}

onMounted(() => {
  scrollToBottom()
})

const sendMessage = async () => {
  if (!newMessage.value.trim() || loading.value) return

  const userMessage = newMessage.value.trim()
  newMessage.value = ''
  loading.value = true

  // 用户消息
  messages.value.push({
    content: userMessage,
    time: new Date(),
    isAI: false
  })

  try {
    const message = await chat({
      userId: getUser().userInfo.id,
      message: userMessage
    })

    if (message.code === 200) {
      messages.value.push({
        content: message.data,
        time: new Date(),
        isAI: true
      })
    } else {
      ElMessage.error(message.message)
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loading.value = false
    await scrollToBottom()
  }
}

const open = () => {
  visible.value = true
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 85vh;
  background-color: #f5f7fa;
  position: relative;
  padding: 20px;
  gap: 20px;

  .chat-header {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    height: 72px;

    .ai-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .ai-title {
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
          font-weight: 500;
        }

        .status {
          font-size: 12px;
          color: #67c23a;
          margin-top: 2px;
          display: block;
        }
      }
    }
  }

  .message-area {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    :deep(.el-scrollbar__wrap) {
      padding: 20px;
    }

    .message-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .message-bubble {
      display: flex;
      max-width: 85%;

      &.ai-message {
        justify-content: flex-start;

        .message-content {
          background-color: #f5f7fa;
          border-radius: 12px 12px 12px 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
      }

      &:not(.ai-message) {
        justify-content: flex-end;

        .message-content {
          background-color: var(--el-color-primary);
          border-radius: 12px 12px 4px 12px;
          color: #fff;

          .message-time {
            color: rgba(255, 255, 255, 0.8);
          }
        }
      }

      .message-content {
        padding: 12px 16px;
        max-width: 100%;
        word-break: break-word;
        overflow-wrap: break-word;

        .message-text {
          margin: 0;
          line-height: 1.6;
          font-size: 14px;
          white-space: pre-wrap;
          word-break: break-word;

          :deep(p) {
            margin: 0;
            white-space: pre-wrap;
          }

          :deep(pre) {
            background-color: #f6f8fa;
            padding: 12px;
            border-radius: 6px;
            overflow-x: auto;
            margin: 8px 0;
            white-space: pre;
          }

          :deep(code) {
            font-family: 'Fira Code', monospace;
            font-size: 13px;
            white-space: pre;
          }

          :deep(ul), :deep(ol) {
            padding-left: 20px;
            margin: 8px 0;
            white-space: pre-wrap;
          }

          :deep(blockquote) {
            border-left: 4px solid #dcdfe6;
            margin: 8px 0;
            padding-left: 12px;
            color: #909399;
            white-space: pre-wrap;
          }
        }

        .message-time {
          font-size: 12px;
          margin-top: 4px;
          display: block;
          text-align: right;
        }
      }
    }
  }

  .input-area {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    height: 160px;

    .el-form {
      display: flex;
      flex-direction: column;
      gap: 12px;
      height: 100%;

      :deep(.el-textarea__inner) {
        border-radius: 8px;
        padding: 12px;
        font-size: 14px;
        line-height: 1.6;
        resize: none;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s;
        max-height: 80px;
        overflow-y: auto;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }

        &:focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }
    }

    .send-button {
      display: flex;
      justify-content: flex-end;
      margin-top: 8px;

      .el-button {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 12px 24px;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover:not(:disabled) {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        }

        &:disabled {
          opacity: 0.7;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
